package com.hl.mystudy.ui.studybinding;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import android.Manifest;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.gyf.immersionbar.ImmersionBar;
import com.hl.mystudy.R;
import com.hl.mystudy.bean.User;
import com.hl.mystudy.databinding.ActivityStudyBindingBinding;
import com.hl.mystudy.ui.studybinding.viewmodel.StudyBindingActivityViewModel;
import com.hl.mystudy.util.LogUtil;
import com.hl.mystudy.util.ToastUtil;
import com.permissionx.guolindev.PermissionX;

/**
 * @author hyhdez
 * @des
 * @date 2023/9/9 22:55
 * @since 1.0
 */
public class StudyBindingActivity extends AppCompatActivity {
    private static final String TAG = StudyBindingActivity.class.getSimpleName();
    public static final String MAIN_FRAGMENT1 = "mainFragment";
    public static final String MAIN_FRAGMENT2 = "mainFragment2";
    private StudyBindingFragment mStudyBindingFragment;
    private StudyBindingFragment2 mStudyBindingFragment2;

    public ActivityStudyBindingBinding getmBinding() {
        return mBinding;
    }

    private ActivityStudyBindingBinding mBinding;
    private User mUser;

    private StudyBindingActivityViewModel mStudyBindingActivityViewModel;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogUtil.i("Enter MainFragment2::onCreate");
        //隐藏系统标题栏
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_study_binding);
        initStatusBarAndToolBar();

        mStudyBindingActivityViewModel = new ViewModelProvider(this).get(StudyBindingActivityViewModel.class);
        mUser = new User("何林", 0, 43);
        mStudyBindingActivityViewModel.setUser(mUser);
        mStudyBindingActivityViewModel.getLiveDataUser().observe(this, user -> {
            mBinding.setUser(user);
        });

        ImmersionBar.with(this)
                .statusBarColor(R.color.colorPrimary)
                .init();


        initFragment();

        doCallWithRequestPermission();


    }

    private void initFragment() {
        mStudyBindingFragment = StudyBindingFragment.newInstance(null, null);
        getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.fragment_container, mStudyBindingFragment, MAIN_FRAGMENT1)
                .commitAllowingStateLoss();


        mStudyBindingFragment2 = StudyBindingFragment2.newInstance(null, null);
        getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.fragment_container2, mStudyBindingFragment2, MAIN_FRAGMENT2)
                .commitAllowingStateLoss();
    }

    private void doCallWithRequestPermission() {
        mBinding.btnCall.setOnClickListener(view -> {
            PermissionX.init(this)
                    .permissions(Manifest.permission.CAMERA, Manifest.permission.READ_CONTACTS,
                            Manifest.permission.CALL_PHONE)
                    .explainReasonBeforeRequest()
                    .onExplainRequestReason((scope, deniedList) -> {
                        scope.showRequestReasonDialog(deniedList, "即将申请的权限是程序必须依赖的权限", "我已明白");
                    })
                    .onForwardToSettings((scope, deniedList) -> {
                        scope.showForwardToSettingsDialog(deniedList, "您需要去应用程序设置当中手动开启权限", "我已明白");
                    })
                    .request((allGranted, grantedList, deniedList) -> {
                        if (allGranted) {
                            ToastUtil.showToastShort(this, "开始拨打电话");
                            mUser.setName("开始拨打电话");
                            mStudyBindingActivityViewModel.setUser(mUser);
                            StudyBindingFragment fragmentByTag = (StudyBindingFragment) getSupportFragmentManager().findFragmentByTag(MAIN_FRAGMENT1);
                            if (fragmentByTag == null) {
                                LogUtil.i("fragmentByTag == null");
                            } else {
                                LogUtil.i("fragmentByTag != null");
                                fragmentByTag.getResult(result -> {
                                    mBinding.tvDataFragment1.setText(result);
                                });
                            }
                        } else {
                            ToastUtil.showToastShort(this, "您拒绝了拨打电话");
                        }
                    });
        });
    }

    /**
     * 初始化状态栏位透明
     * 初始化ToolBar并和ActionBar关联
     */
    private void initStatusBarAndToolBar() {
        // 方法一
        WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
        layoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | layoutParams.flags);

        // 方法二
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

        //当toolbar不连接到系统状态栏时使用这个属性加载资源文件
        //toolbar.inflateMenu(R.menu.zhihu_toolbar_menu);
        //将toolbar连接到系统状态栏
        setSupportActionBar(mBinding.toolbar);
        //设置导航栏图标
//        toolbar.setNavigationIcon(R.mipmap.ic_launcher);
        // toolbar.setLogo(R.mipmap.ic_launcher);//设置app log 一般app只设置一个就可以了 如果你想要的话也可以设置

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            setImmerseLayout(toolbar);
//        }
    }


    protected void setImmerseLayout(View view) {// view为标题栏
        //当版本是4.4以上
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            int statusBarHeight = getStatusBarHeight(this.getBaseContext());
            view.setPadding(0, statusBarHeight, 0, 0);
        }
    }

    public int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        Log.i(TAG, "resourceId = " + resourceId);
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }


    /**
     * 将toolbar连接到系统状态栏必须调用的方法
     * 注：也可以不用链接系统状态栏就不需要调用这个方法 直接用tool的点击监听
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //在return之前加载出toolbar要加载的资源文件
        getMenuInflater().inflate(R.menu.menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    /**
     * 这个方法是菜单的点击监听
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_search) {
            ToastUtil.showToastShort(this, item.getTitle().toString());
        } else {
            ToastUtil.showToastShort(this, item.getTitle().toString());
        }

        return false;
    }

}